package com.ayit.friend.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWTPayload;
import com.alibaba.fastjson.JSON;
import com.ayit.friend.pojo.dto.UserDTO;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

import java.util.HashMap;
import java.util.Map;

public class JWTTokenUtil {
    public static String getToken(UserDTO userDTO){
        String string = JSON.toJSONString(userDTO);
        DateTime dateTime = DateTime.now();
        DateTime newTime = dateTime.offsetNew(DateField.HOUR,1);
        Map<String,Object> payload = new HashMap<>();
        payload.put(JWTPayload.ISSUED_AT,dateTime);
        payload.put(JWTPayload.EXPIRES_AT,newTime);
        payload.put("user",string);
        String key = "root";
        String token = cn.hutool.jwt.JWTUtil.createToken(payload,key.getBytes());
        return token;
    }
    public static UsernamePasswordAuthenticationToken parseUser(Object userDTOString){
        UserDTO userDTO = JSON.parseObject((String) userDTOString, UserDTO.class);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDTO,null,userDTO.getAuthorities());
        return authenticationToken;
    }
}
